/*
 * @Author: youngqj youngqj@126.com
 * @Date: 2024-11-01 22:44:39
 * @LastEditors: youngqj youngqj@126.com
 * @LastEditTime: 2024-12-03 16:35:20
 * @FilePath: /mallSystem/middleware/redis_middleware.go
 * @Description:
 *
 * Copyright © Zhejiang Xiaoqu Information Technology Co., Ltd, All Rights Reserved.
 */
package middleware

import (
	"fmt"
	"xiaoquio/web/core/cache"
	"xiaoquio/web/core/utils"

	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
)

var (
	redisManager *cache.RedisManager
)

func RedisMiddleware(name string) gin.HandlerFunc {

	return func(c *gin.Context) {
		// 检查上下文中是否已存在 Redis 实例
		redisClient, exists := c.Get("redis")
		if exists && redisClient != nil {
			// 如果已存在，直接使用
			c.Next()
			return
		}

		var err error
		redisManager, err = cache.NewRedisManager("cache.yaml")
		if err != nil {
			fmt.Printf("Failed to initialize redisManager: %v\n", err)
		}

		client := redisManager.Clients[name]

		if client == nil {
			utils.ResponseNilData(c, 500, "Redis client not found")
			c.Abort()
			return
		}

		// 将 Redis 客户端存储到上下文中
		c.Set("redis", client)

		// 继续处理请求
		c.Next()
	}
}

// GetRedis 从上下文中获取 Redis 客户端
func GetRedis(c *gin.Context) (*redis.Client, error) {
	redisClient, exists := c.Get("redis")
	if !exists || redisClient == nil {
		return nil, fmt.Errorf("Redis client not found in context")
	}
	client, ok := redisClient.(*redis.Client)
	if !ok {
		return nil, fmt.Errorf("Failed to assert Redis client type")
	}
	return client, nil

}
